package ThreadTest.SaleTicket;

import java.util.ArrayList;

/*
车票类
 */
public class Ticket {
    //集合用来存放车票
    ArrayList<Ticket> arrayList = new ArrayList<>();
    private String name;

    public Ticket() {
    }

    public Ticket(String name){
        this.name = name;
    }

    //给该方法加上一个对象锁
    public synchronized void saleTicket() throws NullTicketException {
        //当车票全部售出时，抛出异常
        if(arrayList.size() == 0){
            throw new NullTicketException("车票已全部售出!");
        }
        //卖出一张票时，在集合中删除卖出的那张车票
        Ticket ticket = arrayList.get(arrayList.size() - 1);
        System.out.println(Thread.currentThread().getName()+ticket.name+"已售出");
        arrayList.remove(ticket);
    }
}
